package com.hmall.trade.listener;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.hmall.api.client.item.ItemClient;
import com.hmall.api.dto.OrderDetailDTO;
import com.hmall.api.dto.PayOrderDTO;
import com.hmall.api.pay.PayClient;
import com.hmall.common.constants.MqConstants;
import com.hmall.pay.domain.po.PayOrder;
import com.hmall.trade.domain.po.Order;
import com.hmall.trade.domain.po.OrderDetail;
import com.hmall.trade.service.IOrderDetailService;
import com.hmall.trade.service.IOrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
@RequiredArgsConstructor
public class OrderDelayMessageListener {

    private final IOrderService orderService;
    private final IOrderDetailService detailService;
    private final ItemClient itemClient;
    private final PayClient payOrderService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MqConstants.DELAY_ORDER_QUEUE_NAME),
            exchange = @Exchange(name = MqConstants.DELAY_EXCHANGE_NAME, delayed = "true", type = ExchangeTypes.DIRECT),
            key = MqConstants.DELAY_ORDER_KEY
    ))
    public void listenOrderDelayMessage(Long orderId) {
        // 1.查询订单
        Order order = orderService.getById(orderId);
        // 2.检测订单状态，判断是否0未支付
        if (order == null || order.getStatus() != 1) {
            // 订单不存在或者不是“未支付”状态 已经处理过的，就直接结束（幂等性校验）
            return;
        }
        // 3.todo 订单状态是未支付，需要查询支付单状态（pay服务里pay_order表的支付单状态）
        PayOrderDTO payOrder = payOrderService.queryPayOrderByBizOrderNo(orderId);

        // 4.判断支付单是否已支付
        //   如果已支付，标记订单状态为"已支付待发货"
        if (payOrder.getStatus() == 3) { // 3：支付成功
            orderService.markOrderPaySuccess(orderId);
        } else {
            //   否则取消订单，回滚库存(查询订单里都有哪些商品，每个商品买了几个)
            // 取消订单(将order表订单状态设置为5)
            Order updateOrder = new Order();
            updateOrder.setId(orderId);
            updateOrder.setStatus(5);
            orderService.updateById(updateOrder);

            // 将订单中已经扣除的商品库存重新加回来
            // 查询订单详情
            List<OrderDetail> orderDetails = detailService.lambdaQuery()
                    .eq(OrderDetail::getOrderId, orderId)
                    .list();

            if (CollectionUtils.isNotEmpty(orderDetails)) {
                // 构造恢复库存所需参数
                List<OrderDetailDTO> orderDetailDTOS = orderDetails.stream().map(detail -> {
                    OrderDetailDTO dto = new OrderDetailDTO();
                    dto.setItemId(detail.getItemId());
                    dto.setNum(detail.getNum());
                    return dto;
                }).collect(Collectors.toList());

                // 恢复库存
                itemClient.deductStock(orderDetailDTOS.stream()
                        .map(dto -> {
                            OrderDetailDTO negativeDto = new OrderDetailDTO();
                            negativeDto.setItemId(dto.getItemId());
                            negativeDto.setNum(-dto.getNum()); // 负数表示恢复库存
                            return negativeDto;
                        })
                        .collect(Collectors.toList()));
            }
        }
    }
}